#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>

#include <shutils.h>

#include "librc.h"

#define USB_DEVICES_FILE	"/proc/bus/usb/devices"
#define USB_DEVPATH_INFO	"/proc/bus/usb/devpath"

/// port_type: 0 - data, 1 - ui
char *usb_modem_get_port(const char *prefix, int port_type)
{
	static char tty[100];
	char tmp[100], str[100];
	FILE *fp;

	do {
		tty[0] = '\0';
		snprintf(str, sizeof(str), ": %s.%s :",
			nvram_prefix_get(prefix, "modem_usbloc"),
			nvram_prefix_get(prefix, port_type == MODEM_PORT_DATA ? "modem_pdata" : "modem_pui"));

		dprintf("Searching: %s.\n", str);

		if ((fp = fopen(USB_DEVPATH_INFO, "rt")) == NULL) {
			dprintf("Error: Not found %s file.\n", USB_DEVPATH_INFO);
			break;
		}
	
		while (fgets(tmp, sizeof(tmp), fp) != 0) {
			char *ptr;
			dprintf("Read: %s", tmp);
			if ((ptr = strstr(tmp, str))){
				*ptr = 0;
				if((ptr = strchr(tmp, ' ')))
					*ptr = 0;
				dprintf("Found %s.\n", tmp);
				snprintf(tty, sizeof(tty), "%s", tmp);
				fclose(fp);
				break;
			}
		}
	} while (0);

	dprintf("done\n");
	return tty;
}